package com.jiubanqingchen.future.org.business.login;


import com.jfinal.aop.Aop;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jiubanqingchen.future.common.tool.MD5Tool;
import com.jiubanqingchen.future.common.tool.SystemTool;
import com.jiubanqingchen.future.model.models.LoginLog;
import com.jiubanqingchen.future.model.models.User;
import com.jiubanqingchen.future.org.admin.BaseService;
import com.jiubanqingchen.future.org.business.log.loginLog.LoginLogService;
import eu.bitwalker.useragentutils.UserAgent;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Light_Dust
 * @ClassName: LoginService
 * @Description: (系统用户登录service)
 * @date 2019年7月4日 下午1:43:55
 */
public class LoginService extends BaseService {

    /**
     * @param @param  user
     * @param @return 参数
     * @return User    返回类型
     * @throws
     * @Title: login
     * @Description: (系统用户登录)
     * @author Light_Dust
     * @date 2019年7月4日 下午1:44:15
     */
    public User login(User user) {
        return User.dao.findFirst(Db.getSql("user.login"), user.getUserAccount(), MD5Tool.md5(user.getUserPassword()));
    }

    /**
     * 处理登录信息
     *
     * @param request 请求
     * @param user    用户信息
     */
    public void handleLoginInfo(HttpServletRequest request, User user) throws Exception {

        //获取请求UserAgent
        UserAgent userAgent = SystemTool.getUserAgent(request);

        //获取ip信息
        Record ipInfo = SystemTool.getIpInfo(request);

        LoginLog loginLog = new LoginLog();

        //存入登录日志
        loginLog.setLoginIp(ipInfo.getStr("ipAddress")).setLoginArea(ipInfo.getStr("ipArea"))
                .setLoginUserName(user.getUserName()).setOs(userAgent.getOperatingSystem().getName()).setBrowser(userAgent.getBrowser().getName());
        LoginLogService loginLogService = Aop.get(LoginLogService.class);
        loginLogService.insert(loginLog, new Record(), user);
    }

}
